package com.ybb.vue.common.security;

import com.ybb.vue.common.constant.JwtConstant;
import com.ybb.vue.entity.CheckResult;
import com.ybb.vue.entity.SysUser;
import com.ybb.vue.service.Impl.SysUserServieceImpl;
import com.ybb.vue.common.util.JwtUtils;
import com.ybb.vue.common.util.StringUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;

/**
 * jwt过滤器
 */
public class JwtAuthenticationFilter extends BasicAuthenticationFilter {

    @Autowired
    private SysUserServieceImpl userServiece;

    @Autowired
    private MyUserDetailsServiceImpl myUserDetailsService;

    private static final String URL_WHITELIST[] = {
            "/login",
            "/image",
            "/logout",
            "/user/register",
            "/webSocket"
    };

    public JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String token = request.getHeader("token");
        System.out.println("请求url：" + request.getRequestURI());
        // url在白名单里则放行
        String url = request.getRequestURI();
        String URL = url.lastIndexOf("/") == 0 ? url : url.substring(0, url.indexOf("/", url.indexOf("/") + 1));
        if (new ArrayList<String>(Arrays.asList(URL_WHITELIST)).contains(URL)) {
            chain.doFilter(request, response);
            return;
        }
        // 验证token
        CheckResult checkResult = JwtUtils.validateJWT(token);
        if (!checkResult.isSuccess()) {
            if (checkResult.getErrCode() == JwtConstant.JWT_ERRCODE_NULL) {
                throw new JwtException(("token不存在"));
            }
            if (checkResult.getErrCode() == JwtConstant.JWT_ERRCODE_EXPIRE) {
                throw new JwtException(("token已过期"));
            }
            if (checkResult.getErrCode() == JwtConstant.JWT_ERRCODE_FAIL) {
                throw new JwtException(("token验证失败，请自重"));
            }
        }
        Claims claims = JwtUtils.parseJWT(token);
        String username = claims.getSubject();
        SysUser user = userServiece.getByUsername(username);
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(username,null,myUserDetailsService.getUserAuthority(user.getId()));
        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
        chain.doFilter(request, response);
    }
}
